﻿using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Validation;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using System;

namespace PMAF.K3Cloud.SCM.Bill.ServicePlugIn
{
    /// <summary>
    /// 校验销售订单采购流水号数量
    /// </summary>
    public class PurchaseSnValidator : AbstractValidator
    {
        public override void Validate(ExtendedDataEntity[] dataEntities, ValidateContext validateContext, Context ctx)
        {
            foreach (ExtendedDataEntity entity in dataEntities)
            {
                string formId = entity["FFormId"].ToString();       //单据类型
                var billId = entity["Id"];
                //var isShort = Convert.ToBoolean(entity["F_PMAF_IsShort"]);
                OQLFilter salOrderFilter = new OQLFilter
                {
                    new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", billId) }
                };
                DynamicObject[] salOrders = BusinessDataServiceHelper.Load(Context, formId, null, salOrderFilter);
                DynamicObjectCollection saleOrderEntries = (DynamicObjectCollection)entity.DataEntity["SaleOrderEntry"];
                //修改订单过程中原订单保留行Id
                int[] oldEntryIds = new int[saleOrderEntries.Count];
                if (string.Equals(formId, "SAL_XORDER"))        //销售订单新变更单
                {
                    foreach (DynamicObject saleOrderEntry in saleOrderEntries)
                    {
                        int currentEntryId = Convert.ToInt32(saleOrderEntry["Id"]);
                        var qty = Convert.ToDecimal(saleOrderEntry["Qty"]);
                        var changeType = saleOrderEntry["CHANGETYPE"].ToString();
                        decimal oldQty = 0;
                        int purchaseId = Convert.ToInt32(saleOrderEntry["F_PMAF_PurchaseSN_Id"]);
                        string purchaseNumber = string.Empty;
                        decimal currentQty = decimal.Zero;
                        if (purchaseId != 0)    //流水号不为空
                        {
                            //设置采购流水号过滤条件并查询流水号
                            OQLFilter purchaseSnFilter = new OQLFilter
                            {
                                new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", purchaseId) }
                            };
                            DynamicObject[] purchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", null, purchaseSnFilter);
                            currentQty = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]);
                            purchaseNumber = purchaseSns[0]["Number"].ToString();

                        }
                        if (Equals(changeType, "B"))        //变更类型为修改
                        {
                            if (salOrders.Length > 0 && purchaseId != 0)  //修改原单并且流水号不为空
                            {
                                DynamicObjectCollection oldEntry = (DynamicObjectCollection)salOrders[0]["SaleOrderEntry"];
                                foreach(DynamicObject entry in oldEntry)
                                {
                                    int oldEntryId = Convert.ToInt32(entry["Id"]);
                                    if(currentEntryId == oldEntryId)
                                    {
                                        oldQty = Convert.ToDecimal(entry["Qty"]);
                                        if(qty - oldQty > currentQty)
                                        {
                                            validateContext.AddError(entity.DataEntity,
                                                new ValidationErrorInfo
                                                ("",
                                                entity.DataEntity["Id"].ToString(),
                                                entity.DataEntityIndex,
                                                entity.RowIndex,
                                                "001",
                                                "明细行第" + (entity.RowIndex + 1) + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                                "保存" + entity.BillNo,
                                                ErrorLevel.Error));
                                        }
                                    }
                                }

                            }
                            else if(salOrders.Length == 0 && purchaseId != 0) //新单并且流水号不为空
                            {
                                oldQty = Convert.ToDecimal(saleOrderEntry["QtyX"]);
                                if (qty - oldQty > currentQty)
                                {
                                    validateContext.AddError(entity.DataEntity,
                                        new ValidationErrorInfo
                                        ("",
                                        entity.DataEntity["Id"].ToString(),
                                        entity.DataEntityIndex,
                                        entity.RowIndex,
                                        "001",
                                        "明细行第" + (entity.RowIndex + 1) + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                        "保存" + entity.BillNo,
                                        ErrorLevel.Error));
                                }
                            }
                        }
                        else if(Equals(changeType, "A"))    //变更类型为新增
                        {
                            if (salOrders.Length > 0 && purchaseId != 0)  //修改原单并且流水号不为空
                            {
                                DynamicObjectCollection oldEntry = (DynamicObjectCollection)salOrders[0]["SaleOrderEntry"];
                                foreach (DynamicObject entry in oldEntry)
                                {
                                    int oldEntryId = Convert.ToInt32(entry["Id"]);
                                    if (currentEntryId == oldEntryId)   //保留行
                                    {
                                        oldQty = Convert.ToDecimal(entry["Qty"]);
                                        if (qty - oldQty > currentQty)
                                        {
                                            validateContext.AddError(entity.DataEntity,
                                                new ValidationErrorInfo
                                                ("",
                                                entity.DataEntity["Id"].ToString(),
                                                entity.DataEntityIndex,
                                                entity.RowIndex,
                                                "001",
                                                "明细行第" + (entity.RowIndex + 1) + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                                "保存" + entity.BillNo,
                                                ErrorLevel.Error));
                                        }
                                    }
                                    else                                //非保留行
                                    {
                                        if (qty > currentQty)
                                        {
                                            validateContext.AddError(entity.DataEntity,
                                                new ValidationErrorInfo
                                                ("",
                                                entity.DataEntity["Id"].ToString(),
                                                entity.DataEntityIndex,
                                                entity.RowIndex,
                                                "001",
                                                "明细行第" + (entity.RowIndex + 1) + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                                "保存" + entity.BillNo,
                                                ErrorLevel.Error));
                                        }
                                    }
                                }
                            }
                            else if(salOrders.Length == 0 && purchaseId != 0)  //新单并且流水号不为空
                            {
                                if (qty > currentQty)
                                {
                                    validateContext.AddError(entity.DataEntity,
                                        new ValidationErrorInfo
                                        ("",
                                        entity.DataEntity["Id"].ToString(),
                                        entity.DataEntityIndex,
                                        entity.RowIndex,
                                        "001",
                                        "明细行第" + (entity.RowIndex + 1) + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                        "保存" + entity.BillNo,
                                        ErrorLevel.Error));
                                }
                            }
                        }
                    }
                }
                else    //销售订单
                {
                    //保存存在的明细行Id
                    int currentIndex = 0;
                    foreach (DynamicObject saleOrderEntry in saleOrderEntries)
                    {
                        //当前行Id
                        int currentEntryId = Convert.ToInt32(saleOrderEntry["Id"]);
                        if (salOrders.Length > 0)   //单据修改
                        {
                            //修改前明细行数据
                            DynamicObjectCollection oldEntry = (DynamicObjectCollection)salOrders[0]["SaleOrderEntry"];
                            foreach (DynamicObject entry in oldEntry)
                            {
                                int oldEntryId = Convert.ToInt32(entry["Id"]);
                                //如果有保留行，放入保留行数组
                                if (currentEntryId == oldEntryId)
                                {
                                    oldEntryIds[currentIndex] = currentEntryId;
                                }
                            }
                        }
                        currentIndex++;
                    }
                    foreach(DynamicObject saleOrderEntry in saleOrderEntries)
                    {
                        int currentEntryId = Convert.ToInt32(saleOrderEntry["Id"]);
                        var qty = Convert.ToDecimal(saleOrderEntry["Qty"]);
                        var purchaseId = Convert.ToInt32(saleOrderEntry["F_PMAF_PurchaseSN_Id"]);
                        var entrySeq = saleOrderEntry["Seq"];
                        //设置采购流水号过滤条件并查询流水号
                        OQLFilter purchaseSnFilter = new OQLFilter
                        {
                            new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", purchaseId) }
                        };
                        DynamicObject[] purchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", null, purchaseSnFilter);
                        bool entryIdExists = Array.Exists(oldEntryIds, element => element == currentEntryId);
                        if(purchaseSns.Length > 0)    //存在流水号
                        {
                            decimal currentQty = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]);
                            string purchaseNumber = purchaseSns[0]["Number"].ToString();
                            if (salOrders.Length > 0)   //修改
                            {
                                DynamicObjectCollection oldEntry = (DynamicObjectCollection)salOrders[0]["SaleOrderEntry"];
                                foreach (DynamicObject entry in oldEntry)
                                {
                                    int oldEntryId = Convert.ToInt32(entry["Id"]);
                                    int oldPurchaseId = Convert.ToInt32(entry["F_PMAF_PurchaseSN_Id"]);
                                    if (entryIdExists)  //当前行数据存在于修改前数据行
                                    {
                                        decimal oldQty = Convert.ToDecimal(entry["Qty"]);
                                        if (currentEntryId == oldEntryId && purchaseId == oldPurchaseId)
                                        {
                                            if (qty - oldQty > currentQty)
                                            {
                                                validateContext.AddError(entity.DataEntity,
                                                    new ValidationErrorInfo
                                                    ("",
                                                    entity.DataEntity["Id"].ToString(),
                                                    entity.DataEntityIndex,
                                                    entity.RowIndex,
                                                    "001",
                                                    "（修改不换号）明细行第" + entrySeq + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                                    "保存" + entity.BillNo,
                                                    ErrorLevel.Error));
                                            }
                                        }
                                        else if(currentEntryId == oldEntryId && purchaseId != oldPurchaseId)
                                        {
                                            if (qty > currentQty)
                                            {
                                                validateContext.AddError(entity.DataEntity,
                                                    new ValidationErrorInfo
                                                    ("",
                                                    entity.DataEntity["Id"].ToString(),
                                                    entity.DataEntityIndex,
                                                    entity.RowIndex,
                                                    "001",
                                                    "（修改换号）明细行第" + entrySeq + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                                    "保存" + entity.BillNo,
                                                    ErrorLevel.Error));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (qty > currentQty)
                                        {
                                            validateContext.AddError(entity.DataEntity,
                                                new ValidationErrorInfo
                                                ("",
                                                entity.DataEntity["Id"].ToString(),
                                                entity.DataEntityIndex,
                                                entity.RowIndex,
                                                "001",
                                                "（修改新增）明细行第" + entrySeq + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                                "保存" + entity.BillNo,
                                                ErrorLevel.Error));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (qty > currentQty)
                                {
                                    validateContext.AddError(entity.DataEntity,
                                        new ValidationErrorInfo
                                        ("",
                                        entity.DataEntity["Id"].ToString(),
                                        entity.DataEntityIndex,
                                        entity.RowIndex,
                                        "001",
                                        "（新增）明细行第" + entrySeq + "行，流水号" + purchaseNumber + "剩余数量为：" + currentQty + ",不够出，请重新填写数量!",
                                        "保存" + entity.BillNo,
                                        ErrorLevel.Error));
                                }
                            }

                        }
                    }
                }
            }
        }
    }
}
